const { Add, Update, QueryOne, ExecGetOne, Exec, Query } = require('../db/dbhelper');
var { init, format } = require('../models/peoplecontact');
var { formatDate, formatDateTime, formatDateYear } = require('../libs/common');
var _ = require('underscore');
var { matchhistoryAdd } = require('./matchhistory');
const logger = require('../libs/log').logger;

// 保存联系人记录
const peoplecontactSave = async function (doc) {
  try {
    return {
      code: 0,
      msg: 'success'
    }
    logger.info('-------------peoplecontactSave---doc', doc)
    if (!doc.pcode) {
      return {
        code: 1,
        msg: 'pcode参数不能为空'
      }
    }
    if (!doc.fcode) {
      return {
        code: 1,
        msg: 'fcode参数不能为空'
      }
    }
    let data = await QueryOne('hzz_peoplecontacts', doc);
    let isok;
    if (data) {
      let his = data.history ? JSON.parse(data.history) : [];
      his.push({
        pcode: data.pcode,
        fcode: data.fcode,
        updatetime: data.updatetime
      });
      doc.history = JSON.stringify(his);
      doc.id = data.id;
      isok = await Update('hzz_peoplecontacts', format(doc));
    } else {
      isok = await Add('hzz_peoplecontacts', init(doc));
    }
    if (isok) {
      let pair = await QueryOne('hzz_peoplecontacts', { pcode: doc.fcode, fcode: doc.pcode });
      if (pair) {// 如果互相联系了对方，则配对成功statu=1
        await Exec(`update hzz_peoples set statu=1 where code in (${doc.fcode},${doc.pcode})`);
        await matchhistoryAdd({ pcode: doc.pcode, fcode: doc.fcode });
      }
      return {
        code: 0,
        msg: 'success'
      }
    }
  } catch (error) {
    logger.info('---------peoplecontactSave---error', error)
    return {
      code: 0,
      msg: 'success'
    }
  }
}

//我的联系人
const peoplecontactForMy = async function (doc) {
  try {
    if (!doc.pcode) {
      return {
        code: 1,
        msg: 'pcode参数不能为空'
      }
    }
    let data = await Exec(`select * from hzz_peoplecontacts where pcode='${doc.pcode}' OR fcode='${doc.pcode}' ORDER BY createtime DESC`);
    let peos = [];
    if (data && data.length) {
      let codestr = _.compact(_.union(_.pluck(data, 'fcode'), _.pluck(data, 'pcode'))).join(',');
      let execsql = 'SELECT code,nickname,avator,age,grender,birthday,star,height,education,year_income FROM hzz_peoples WHERE CODE IN (' + codestr + ')';
      peos = await Exec(execsql);
    }
    let rdata = [];
    _.map(data, function (item) {
      let peoplecode = item.fcode == doc.pcode ? item.pcode : item.fcode;
      let isadd = _.find(rdata, function (p) {
        return p.code == peoplecode;
      })
      if (!isadd) {
        let people = _.find(peos, function (po) {
          return po.code == peoplecode;
        })
        if (people) {
          people.birthday = formatDateYear(people.birthday);
          rdata.push({
            code: peoplecode,
            info: people,
            createtime: formatDateTime(item.createtime)
          });
        }
      }
    })
    return {
      code: 0,
      data: rdata
    };
  } catch (error) {
    return {
      code: 1,
      msg: error ? error.message : '获取异常'
    }
  }
}

module.exports = {
  peoplecontactSave,
  peoplecontactForMy
}